#!/usr/bin/env python3
# -*- coding:utf-8 -*-

import os
from abc import ABC
from ctools.common.fsmonitor import BaseFileWatcher

def new_basename(filename:str, _from:str, _to:str):
    bname = os.path.basename(filename)
    pos = bname.rfind(_from)
    if pos >= 0:
        return bname[:pos] + _to
    return bname

def new_filepath(filepath:str, func=lambda bname: bname):
    fdir = os.path.dirname(filepath)
    bname = os.path.basename(filepath)
    return os.path.join(fdir, func(bname))

class FileWorkerBase(BaseFileWatcher, ABC):
    @classmethod
    def can_work(cls):
        return True

    @classmethod
    def is_match(cls, filename):
        return False

    @classmethod
    def handle_new(cls, filepath:str, opts=None):
        cmd = f'touch {filepath}'
        os.system(cmd)

    @classmethod
    def _handle_remove_files(cls, filepath:str, opts=None) -> list|tuple:
        return (filepath,)

    @classmethod
    def handle_remove(cls, filepath:str, opts=None):
        try:
            all_files = cls._handle_remove_files(filepath, opts)
            input(f"press enter to remove files")
            cmd = f'rm -f {" ".join(all_files)}'
            os.system(cmd)
        finally:
            pass

    @classmethod
    def handle_dump(cls, filepath:str, opts=None):
        cmd = f'cat {filepath}'
        os.system(cmd)
